package com.bort.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bort.system.mapper.RoleMapper;
import com.bort.system.mapper.RoleMenuMapper;
import com.bort.system.model.Role;
import com.bort.system.model.RoleMenu;
import com.bort.system.service.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    RoleMapper roleMapper;

    @Resource
    RoleMenuMapper roleMenuMapper;

    @Override
    public List<Role> selectAll(String name) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.lt("status",2);
        wrapper.gt("status",0);
        if(StringUtils.isNotEmpty(name)){
            wrapper.like("role_name","%"+""+name+"%");
        }
        return roleMapper.selectList(wrapper);

    }

    @Override
    public void add(Role role) {
        roleMapper.insertSelective(role);
    }

    @Override
    public void delete(Integer id) {
        roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void saveRoleMenus(JSONObject params) {
        List<RoleMenu> list = new ArrayList<>();
        JSONArray keys = params.getJSONArray("keys");
        int roleId = params.getIntValue("roleId");
        this.deleteRoleMenusByRoleId(roleId);
        for (int i = 0; i < keys.size(); i++) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(keys.getIntValue(i));
            list.add(roleMenu);
        }
        roleMapper.saveRoleMenus(list);
    }

    private void deleteRoleMenusByRoleId(int roleId) {
       int del = roleMenuMapper.deleteByRoleId(roleId);
    }
}
